<!-- @format -->

<script setup lang="ts">
import viewNodeText from './viewNodeText.vue'
import viewNodeIcon from './viewNodeIcon.vue'
import TheIcon from '@/components/TheIcon.vue'
import { TYPE_TEXT, TYPE_ICON } from './viewNodeType.ts'
import { defineProps, computed, ref, effect } from 'vue'

const props = defineProps({
  conf: {},
})

const emit = defineEmits(['click', 'remove'])

const type = computed(() => {
  const result = props.conf.type || ''
  return result
})

// 新增拖拽逻辑
const isDragging = ref(false)
const isMoving = ref(false)
const showRemove = ref(false)
const startX = ref(0)
const startY = ref(0)
const pos = ref({ x: props.conf.x || 0, y: props.conf.y || 0 })
const hasRemove = ref(false)

const onTouchStart = (e) => {
  isDragging.value = true
  const [touch] = e.touches
  startX.value = touch.clientX - pos.value.x / 2
  startY.value = touch.clientY - pos.value.y / 2
}

const changeConf = (value) => {
  emit('change', {
    ...props.conf,
    ...value,
  })
}

const onTouchMove = (e) => {
  if (!isDragging.value) return
  isMoving.value = true
  const [touch] = e.touches
  pos.value = {
    x: (touch.clientX - startX.value) * 2,
    y: (touch.clientY - startY.value) * 2,
  }
}

let hideId = 0
const delayHide = () => {
  if (hideId > 0) clearTimeout(hideId)
  hideId = setTimeout(() => {
    showRemove.value = false
  }, 1500)
}

const onTouchUp = () => {
  if (!isMoving.value) {
    emit('click')
  }
  isMoving.value = false
  isDragging.value = false
  showRemove.value = true
  delayHide()
  changeConf(pos.value)
}

effect(() => {
  pos.value = {
    x: props.conf.x || 0,
    y: props.conf.y || 0,
  }
})

// const onRemove = () => {
//   if (!showRemove.value) return
//   hasRemove.value = true
//   console.log('remove')
//   emit('remove')
// }
</script>

<template>
  <div
    class="view-node"
    :class="{ active: isDragging }"
    :style="{ transform: `translate(${pos.x}rpx, ${pos.y}rpx)` }"
    @touchstart="onTouchStart"
    @touchmove.stop="onTouchMove"
    @touchend="onTouchUp"
  >
    <!-- <the-icon
      icon="minus-circle-filled"
      class="btn-close"
      :class="{ active: showRemove }"
      @touchstart.stop="onRemove"
    ></the-icon> -->
    <view-node-text v-if="type === TYPE_TEXT" :conf="conf"></view-node-text>
    <view-node-icon v-if="type === TYPE_ICON" :conf="conf"></view-node-icon>
  </div>
</template>

<style scoped>
.view-node {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  user-select: none;
}
.view-node.active {
  outline: 2px solid #2196f3;
}
.btn-close {
  position: absolute;
  right: -20rpx;
  top: -20rpx;
  opacity: 0;
  transition: opacity 0.5s linear;
}
.btn-close.active {
  opacity: 1;
}
</style>
